import { Table } from 'antd';
import type { TableRowSelection } from 'antd/es/table/interface';
import { Dispatch, Key, SetStateAction } from 'react';
import { DesignTableColumn } from '@app-cad/common/commands/cmd-design-table/types';

interface ColumnParameterLinkageProps {
  dataSource: DesignTableColumn[];
  selectedColumns: number[];
  setSelectedColumns: Dispatch<SetStateAction<number[]>>;
}

export function ColumnParameterLinkage({
  dataSource,
  selectedColumns,
  setSelectedColumns,
}: ColumnParameterLinkageProps) {
  const columns = [
    {
      title: '参数',
      dataIndex: 'parameterLabel',
      key: 'parameterLabel',
    },
    {
      title: '表列',
      dataIndex: 'column',
      key: 'column',
    },
  ];

  const rowSelection: TableRowSelection<DesignTableColumn> = {
    type: 'checkbox',
    selectedRowKeys: selectedColumns,
    onChange: (newSelectedKeys: Key[]) => {
      setSelectedColumns(newSelectedKeys as number[]);
    },
  };

  return (
    <div className='w-[358px] h-[210px] border border-gray-300 select-none'>
      <Table
        columns={columns}
        dataSource={dataSource}
        rowSelection={rowSelection}
        pagination={false}
        scroll={{ y: 170 }}
        size='small'
        onRow={(record) => ({
          onClick: () => {
            let newSelected: number[];
            if (selectedColumns.includes(record.key)) {
              newSelected = selectedColumns.filter((k) => k !== record.key);
            } else {
              newSelected = [...selectedColumns, record.key];
            }
            setSelectedColumns(newSelected);
          },
        })}
      />
    </div>
  );
}
